
#include "MyButton.h"
MyButton ::MyButton(void) : preMillis(10000000L), Mode(MyDisplay::MODE_RUN), setButtonPressed(false), increaseCount(0), decreaseCount(0)
{
    pinMode(BUTTON_FUNC_PIN, INPUT_PULLUP);
    attachInterrupt(BUTTON_FUNC_PIN, std::bind(&MyButton::isr_func, this), FALLING);

    pinMode(BUTTON_INC_PIN, INPUT_PULLDOWN);
    attachInterrupt(BUTTON_INC_PIN, std::bind(&MyButton::isr_inc, this), RISING);

    pinMode(BUTTON_DEC_PIN, INPUT_PULLDOWN);
    attachInterrupt(BUTTON_DEC_PIN, std::bind(&MyButton::isr_dec, this), RISING);

    pinMode(BUTTON_SET_PIN, INPUT_PULLDOWN);
    attachInterrupt(BUTTON_SET_PIN, std::bind(&MyButton::isr_set, this), RISING);
}

MyButton ::~MyButton(void)
{
}

void IRAM_ATTR MyButton ::isr_func()
{
    onButton();
}

void IRAM_ATTR MyButton ::isr_inc()
{
    unsigned long currentMillis = millis();
    unsigned long diff = abs(currentMillis - preMillis);
    if (diff < 200) //防抖
    {
        return;
    }
    if (diff < 500) //快速按下，一次加10
    {
        increaseCount += 10;
    }
    else
    {
        increaseCount++;
    }

    //Serial.printf("inc=%d\n", increaseCount);

    preMillis = currentMillis;
}

void IRAM_ATTR MyButton ::isr_dec()
{
    unsigned long currentMillis = millis();
    unsigned long diff = abs(currentMillis - preMillis);
    if (diff < 200) //防抖
    {
        return;
    }
    else if (diff < 500) //快速按下，一次加10
    {
        decreaseCount += 10;
    }
    else
    {
        decreaseCount++;
    }
    //Serial.printf("dec=%d\n", decreaseCount);
    preMillis = currentMillis;
}

void IRAM_ATTR MyButton ::isr_set()
{
    unsigned long currentMillis = millis();
    unsigned long diff = abs(currentMillis - preMillis);
    if (diff < 200) //防抖
    {
        return;
    }
    else
    {
        setButtonPressed = true;
        //  Serial.println("set");
        preMillis = currentMillis;
    }
}
void MyButton::onButton()
{
    unsigned long currentMillis = millis();
    unsigned long diff = abs(currentMillis - preMillis);

    if (Mode != MyDisplay::MODE_RUN) //非运行模式
    {
        if (diff < 200) //防抖
        {
            return;
        }
        preMillis = currentMillis;
        onButtonAct(); //切换到下一个模式
        return;
    } //运行模式，双击判断
    else
    {
        if (diff > 1500) //超期,更新时间
        {
            preMillis = currentMillis;
            //Serial.println("first press");
            return;
        }
        else if (diff < 200) //防抖
        {
            return;
        }
        else
        { //双击
            //Serial.println("double press");
            preMillis = currentMillis;
            onButtonAct(); //切换模式
        }
    }
}

////切换模式/////////
void MyButton::onButtonAct()
{
    Mode++;
    if (Mode > MyDisplay::MODE_END)
    {
        Mode = MyDisplay::MODE_RUN;
    }
}